<?php

namespace System\Core;

if (!defined('BASEPATH')) die('Access Denied.');

/**
 * µMVC Framework (c) 2011.
 * 
 * PHP5 MVC Framework software for PHP 5.2.17 or later
 * 
 * @package         µMVC
 * @filename        system/core/config.class.php
 * @copyright       Lanz (c) 2011.
 * 
 */

class ConfigException extends CommonException {}

/**
 * Config class
 * Selects and access the appropriate config based on the ENVIRONMENT definition.
 * 
 * @package         µMVC
 * @subpackage      Core
 * @category        System
 */
class Config extends BaseSingleton
{

    /**
     * The path to the config file.
     * @var string 
     */
    private $_filePath;
    
    /**
     * The config file is only read once and then stored here.
     * @var array
     */
    private $_config = null;
    
    function __construct()
    {
        if (defined('ENVIRONMENT') AND is_readable(BASEPATH.'configs'.DS.ENVIRONMENT.DS.'config.php'))
        {
            $this->_filePath = BASEPATH.'configs'.DS.ENVIRONMENT.'config.php';
        }
        elseif (is_readable(BASEPATH.'configs'.DS.'config.php'))
        {
            $this->_filePath = BASEPATH.'configs'.DS.'config.php';
        }
        else
        {
            throw new ConfigException('The configuration file does not exist.');
        }   
    }

    public function getConfig()
    {
        if (!is_null($this->_config))
        {
            return $this->_config;
        }
        
        include_once $this->_filePath;
        
        if (!isset($config) OR !is_array($config))
        {
            throw new ConfigException('Your config file does not appear to be formatted correctly.');
        }
        
        $this->_config = $config;
        
        return $config;
    }
    
    public function getItem($key, $return = FALSE)
    {
        $config = $this->getConfig();

        if (isset($config[$key]))
        {
            return $config[$key];
        }
        else
        {
            return $return;
        }
    }
}
?>
